import pandas as pd
import os
from django.core.management.base import BaseCommand
from exams.models import LogistQuestion, ChoiceOption

class Command(BaseCommand):
    help = '从Excel文件导入题目数据（支持题干和选项图片）'

    def add_arguments(self, parser):
        parser.add_argument('excel_file', type=str, help='LogistQuestions.xlsx')
        parser.add_argument('--clear', action='store_true', help='导入前清空现有数据')

    def handle(self, *args, **options):
        excel_file = options['excel_file']
        clear_existing = options['clear']

        if not os.path.exists(excel_file):
            self.stdout.write(self.style.ERROR(f'文件不存在: {excel_file}'))
            return

        if clear_existing:
            self.stdout.write('清空现有题目数据...')
            LogistQuestion.objects.all().delete()
            self.stdout.write(self.style.SUCCESS('现有数据已清空'))

        try:
            df = pd.read_excel(excel_file)
            self.stdout.write(f'成功读取Excel文件，共{len(df)}行数据')

            success_count = 0
            error_count = 0

            for index, row in df.iterrows():
                try:
                    # 题目类型转换
                    qtype = 1 if str(row['题目类型']).strip() == '选择题' else 2

                    # 题干图片
                    stem_image_name = str(row['题干图片']).strip() if '题干图片' in row and pd.notna(row['题干图片']) else ''
                    stem_image_path = f"question_images/{stem_image_name}" if stem_image_name else None

                    question = LogistQuestion.objects.create(
                        question_id=str(row['题目ID']).strip(),
                        stem=str(row['题干内容']).strip(),
                        stem_image=stem_image_path,
                        question_type=qtype,
                        topic=str(row['主题']).strip(),
                        score=int(row['分值']),
                        answer=str(row['答案']).strip() if not pd.isna(row['答案']) else ''
                    )

                    # 选择题导入选项及图片
                    if qtype == 1:
                        for option in ['A', 'B', 'C', 'D']:
                            option_col = f'选项{option}'
                            option_content = row[option_col] if option_col in row and pd.notna(row[option_col]) else ''
                            option_image_col = f'选项{option}图片'
                            option_image_name = str(row[option_image_col]).strip() if option_image_col in row and pd.notna(row[option_image_col]) else ''
                            # 只要内容或图片有一个不为空就导入
                            if (isinstance(option_content, str) and option_content.strip()) or option_image_name:
                                ChoiceOption.objects.create(
                                    question=question,
                                    label=option,
                                    content=option_content,
                                    option_image=option_image_name if option_image_name else None
                                )

                    success_count += 1
                    if success_count % 10 == 0:
                        self.stdout.write(f'已导入 {success_count} 道题目...')

                except Exception as e:
                    error_count += 1
                    self.stdout.write(self.style.ERROR(f'第{index+1}行导入失败: {str(e)}'))

            self.stdout.write(self.style.SUCCESS(f'导入完成！成功: {success_count}, 失败: {error_count}'))

        except Exception as e:
            self.stdout.write(self.style.ERROR(f'导入过程中发生错误: {str(e)}'))